package com.huluobo.base.mvvm

import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.DatePicker
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 *  Created by LC on 2024/9/2.
 */
abstract class BaseActivity<VDB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }
    protected val binding: VDB by lazy {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null, layoutInflater) as VDB
    }

    protected val viewModel: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    open fun onError(t: Throwable) {
        ToastUtils.showLong(t.message)
        Log.i("TagA", "t:${t.message}")
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        viewModel.onFailed.observe(this, ::onError)
        initView()
        initData()
    }

    abstract fun initData()

    abstract fun initView()

    fun getTime(): String {
        val time = System.currentTimeMillis()
        var tampTime = TimeUtils.millis2String(time, SimpleDateFormat("yyyy-MM-dd"))
        tampTime += "T"
        tampTime += TimeUtils.millis2String(time, SimpleDateFormat("hh:mm:ss"))
        tampTime += "Z"
        return tampTime
    }

    fun showDateDialog(textView: TextView) {
        val calendar = Calendar.getInstance()
        DatePickerDialog(
            this,
            { view, year, month, dayOfMonth ->
                textView.text = "$year-${month + 1}-$dayOfMonth"
            },
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }
}